/**
 * Created by chm on 2016/4/18.
 */

//添加jquery自定义验证，通过正则表达式验证密码
jQuery.validator.addMethod("passwordValidate",function(value,element){
	
	var regex = /^[0-9a-zA-Z_]{6,12}$/;
	return this.optional(element)||(regex.test(value));
		
	},"密码6-12位，由字母、数字或下划线组成，请重新输入！");


isUserNameValidator();
var loadDiv = null;
$(function () {
	loadDiv = $("#loadDiv").loading();//初始化提示操作执行中
    initUpdateWindow(jqp);
    initUpdateForm();
});

/*function createEditWindow(id, label, formId, options){
	options = $.extend({
        width: 400,
        height: 300
    },options || {});
	//初始化添加窗口
    var addWindow = $("#" + id);
    addWindow.dialog({
        autoOpen: false,
        width: options.width,
        height: options.height,
        resizable: false,
        title: label,
        modal: true,
        buttons: {
            "保存": function () {
                $("#" + formId).submit();
            },
            "取消": function () {
                $(this).dialog("close");
            }
        },
        close: function(){
        	$(".jBox-wrapper").remove();
        }
    });
    return addWindow;
}*/

/**
 * 初始化表单数据
 */
function initUpdateForm(){
    var selectList = new Array();
    $("#deptTable tr td :checkbox").each(function () {
        if (this.checked)
            selectList[selectList.length] = $(this).attr("id");
    });
    $("#updatePassword").val("000000");
//    getRolesWithoutSuper();//加载角色列表并选中
    getDeptsByCurrUser();//加载部门列表并选中
    getSex();//加载性别并选中
}

//function getRolesWithoutSuper(){
//	post(getPath() + "base/role/tree",{},function(result){
//        if(result.length > 0){
//            var areaHtml = "";
//            for(var i=0; i < result.length; i++){
//                var item = result[i];
//                areaHtml += "<option value='" + item.id + "'>" + item.name + "</option>";
//            }
//            $("#updateRole").html(areaHtml);
//            $("#updateRole").val($("#updateRoleTemp").val());//选中角色
//        }
//	});
//}

function getDeptsByCurrUser(){
	post(getPath() + "org/department/tree",{pid:0},function(result){
		if(result.length > 0){
			var areaHtml = "";
			for(var i=0; i < result.length; i++){
				var item = result[i];
				areaHtml += "<option value='" + item.id + "'>" + item.name + "</option>";
			}
			$("#updateDepartment").html(areaHtml);
			$("#updateDepartment").val($("#updateDepartmentTemp").val());//选中部门
		}
	});
}
function getSex(){
	$("#updateSex").val()=="男" ? $("#updateSex1").attr("checked","checked")
			:$("#updateSex").val()=="女"? $("#updateSex2").attr("checked","checked")
			:$("#updateSex1").attr("checked","checked");}

/**
 * 初始化更新窗口
 * @returns {Function}
 */
function initUpdateWindow(jqp){

    //声明消息提示
    var toolTips = new Object();
    //var oldUserName = "";

    //设置表单验证
    var validator = $("#updateForm").validate({   	
    	rules:{
        	userName:{
        		required:true,
        		userNameValidate:true,
        		remote:{
        			url: getPath() +  "base/user/validateUser",
        			type: "post",
        			data:{
        				newName:function(){return $("#updateUserName").val();},
    					oldName:function(){return oldUserName;}
        			}        			
        		}
        	},
        	password:{
        		required:true,
        		passwordValidate:true
        	}
   	
        },
        messages:{
        	userName: {
        		required:"请输入用户名！",
        		remote: "已存在此用户名，请重新输入！"
        	},
        	password: {
        		required:"请输入密码！"
	        }
        },
        errorPlacement: function(eror,element){
            var toolTip = createTooltip(toolTips,element.attr("id"));
            toolTip.setContent(eror.text());
            toolTip.close();
            element.addClass("error-border");

        },
        success:function(label){
            var elementId = label.attr("id").substring(0,label.attr("id").length - 6);
            var toolTip = toolTips[elementId];
            $("#" + elementId).removeClass("error-border");
            toolTip.close();
            toolTip.detach();
        },	    	    	
        submitHandler:function(form){
        	loadDiv.showLoading();
            post(getPath() + "base/user/edit",
                $("#updateForm").serialize(),
                function(resultObject){
                var errors = resultObject.errors;
                //判断后台是否有返回错误消息
                if(errors && errors.length > 0){
                	loadDiv.hideLoading();
                    for(var i=0; i < errors.length; i++){
                        var error = errors[i];
                        var toolTip = createTooltip(toolTips,"update" + error.field);
                        toolTip.setContent(error.defaultMessage);
                        $("#update" + error.field).addClass("error-border");
                    }
                }else{
                	loadDiv.hideLoading();
                    //更新成功，弹出添加成功提示框，当用户点击确定后刷新页面
                    createWindow("修改成功",{url: getPath() + "base/user/list/" + jqp.data('jqPaginator').options.currentPage + "/" + pageSize + '?' +
						($("#isFilter").val() == 1 ? ("?" + $("#searchForm").serialize()) : "")}).dialog("open");
                }
		},function(resultObject){
			loadDiv.hideLoading();
    		createWindow(resultObject).dialog('open');
    	});
        }
    });
  //隐藏列表，显示添加
	$('#dialog').show();
	$('.grid-list').hide();
	//取消
	$('#cancleBtn').click(function(){
		$('#dialog').hide();
		$('.grid-list').show();
	});
}



//=================判断电话号码是否唯一========================
$("#telephone").blur(function(){
	/*jQuery.validator.addMethod("isPhone", function(value,element) { 
		var mobile = /^1[34578]\d{9}$/; //手机号
		var tel = /^(\d{3,4}-)?\d{7,8}$/; //固话号
		return this.optional(element) || (mobile.test(value)) || (tel.test(value)); 
	}, "请正确填写号码"); */
	if(!(/^1[34578]\d{9}$/.test($("#telephone").val()))){
		document.getElementById("telephoneSpan").innerText = " 请填写正确的电话号码!";
	}else{
		$.ajax({
			type:"post",
			url:getPath() +  "base/user/validateTelephone",
			//contentType: "application/json; charset=utf-8",
			dataType: "json",//表示后台返回的数据是json对象
			data :{
				newTelephone:function(){
				return $("#telephone").val();}
			},
			success: function (data) {
				if(data==true){
					document.getElementById("telephoneSpan").innerText = "";
				}else if(data==false){
					document.getElementById("telephoneSpan").innerText = " 号码已存在!";
				}
			},
			error: function (error) {
				
			}
		});
	}
});


